'use client';

import style from './ProductsGroup.module.scss';
import { useIntersection } from 'react-use';
import { IProductsGroup } from '@/components/shared/ProductsGroup/types';
import { FC, useEffect, useRef } from 'react';
import { Title } from '@/components/shared/Title';
import ProductCard from '@/components/shared/ProductCard/ProductCard';
import { useCategory } from '@/store/category';


const ProductsGroup:FC<IProductsGroup> = ({
  title,
  items,
  listClassName,
  categoryId,
  className,
}) => {
  const setActiveCategoryId = useCategory((state) => state.setActiveId);
  const intersectionRef = useRef(null);
  const intersection = useIntersection(intersectionRef, {
    threshold: 0.4,
  });

  useEffect(() => {
    if (intersection?.isIntersecting) {
      setActiveCategoryId(categoryId);
    }
  }, [categoryId, intersection?.isIntersecting, title]);


  return (
    <div
      className={style.productsGroup}
      ref={intersectionRef}
      id={title}
    >
      <Title text={title} className={className} />

      <div className={`${style.productsGroup__wrapper} ${listClassName}`}>
        {items.map((item) => (
          <ProductCard
            key={item.id}
            id={item.id}
            name={item.name}
            imageUrl={item.items[0].imageUrl}
            price={item.items[0].price}
            description={item.items[0].description}
          />
        ))}
      </div>

    </div>
  );
};

export default ProductsGroup;
